<?php
function commstack( $input, &$output)
{
    $opres  = "Error. Unexpected internal error.";
    $output = NULL;

    $docroot = dirname($_SERVER['DOCUMENT_ROOT']);

    $tmpfname = tempnam("/tmp", "commstack");
    $handle = popen($docroot.'/lib/commstack/scripts/commstack >'.$tmpfname, 'w');

    if (is_resource($handle)) 
    {
	for( $i=0; $i<count($input); $i++ ) 
	    fwrite($handle, $input[$i]);
	    
	
	pclose($handle);

	$sres = file_get_contents($tmpfname);

	$ares = explode( "\n", $sres );

//    print_r( $ares ); echo "<br>\n";

// Last Line always ampty
	$icount = count($ares)-1;
    
// Last output line must be result code
	$icount--;
	
	if( $icount >= 0 ) {
	    $k = 0;
	    for( $i=0; $i<$icount; $i++ ) {
		$ares[$i] = trim($ares[$i]);
		if( empty($ares[$i])) continue;
		$output[$k] = $ares[$i];
		$k++;
	    }
	    $opres = $ares[$icount];
	}
	else
	    $opres = "Script 'commstack' not return any data.";
    }
    else
	$opres = "Error. Executing script 'commstack'.";

//    unlink($tmpfname);

    return $opres;
}
